<template>
  <div style="padding: 15px;">
    <el-form ref="form" :rules="rules" :model="form" label-width="80px">
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="所属仓库" prop="warehouseCode">
              <warehouseSelect ref="warehouseSelect"  @setWarehouseCode="setWarehouseCode" style="width: 75%"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="入驻商" prop="shipmentCode" label-width="100px">
              <shipmentSelect3 ref="shipmentSelect3"  @setShipmentInfo="setShipmentInfo" style="width: 75%"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="来源单号" prop="sourceCode">
              <el-input v-model="form.sourceCode" style="width:75%"  />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="供应商" prop="supplierCode">
              <supplierSelect ref="supplierSelect"  @setsupplierCode="setsupplierCode" style="width: 75%"/>
            </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item  label="计划到货日期" label-width="100px">
              <el-date-picker
                v-model="form.gmtPlanArrival"
                value-format="yyyy-MM-dd"
                align="right"
                style="width:75%"
                type="date"
                placeholder="选择日期"
              />
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="19">
          <div class="grid-content bg-purple">
            <el-form-item  label="备注" prop="remarks">
              <el-input v-model="form.remarks" style="width:75%"  />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <vxe-toolbar id="toolbar_demo3">
      <template v-slot:buttons>
        <el-button @click="insertEvent">新增明细</el-button>
      </template>
    </vxe-toolbar>
    <vxe-table
      border
      resizable
      keep-source
      show-overflow
      ref="xTable"
      :align="allAlign"
      :data="tableData"
      show-footer
      :footer-method="footerMethod"
      :edit-rules="validRules"
      :edit-config="{trigger: 'click', mode: 'cell'}">
      <vxe-table-column type="seq" width="60"></vxe-table-column>
      <vxe-table-column field="goodsName" title="商品名称" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <goodsSelect  :val2="form.shipmentCode" ref="goodsSelect"  @setGoodsCode="setGoodsCode(row)" />
        </template>
      </vxe-table-column>
      <vxe-table-column field="goodCode" title="商品编码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsBarCode" title="商品条码"  width="120"></vxe-table-column>
      <vxe-table-column field="goodsUnitName" title="单位"  :edit-render="{}" width="270">
        <template v-slot:edit="{ row }">
          <el-select v-model="row.goodsUnitName" placeholder="请输入单位" style="width:100%" @change="nameChangeEvent(row)" >
            <el-option
              v-for="item in row.goodsUnitConversionList"
              :key="item.unitName"
              :label="item.unitName"
              :value="item.unitName"
            />
          </el-select>
        </template>
      </vxe-table-column>
      <vxe-table-column field="planQuantity" title="数量" :edit-render="{name: 'input'}" width="120" ></vxe-table-column>
      <vxe-table-column field="unit" title="单位换算" width="270" ></vxe-table-column>
      <vxe-table-column field="basicUnitName" title="基本单位"   width="120"></vxe-table-column>
      <vxe-table-column field="sumBasicQuantity" title="数量" width="120" >
        <template v-slot="{ row }">
          <span>{{ isNaN(row.unitConvertQuantity * row.planQuantity)?0:row.unitConvertQuantity * row.planQuantity}}</span>
        </template>
      </vxe-table-column>
      <vxe-table-column field="remarks" title="备注" :edit-render="{name: 'input'}" width="270"></vxe-table-column>
      <vxe-table-column title="操作" fixed="right" min-width="50">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="删除" placement="top">
            <vxe-button type="text" @click="removeRow(scope.row)">
              <i class="el-icon-delete" />
            </vxe-button>
          </el-tooltip>
        </template>
      </vxe-table-column>
    </vxe-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitData(0)" :disabled="isDisable" plain>保 存</el-button>
      <el-button type="primary" @click="submitData(1)" :disabled="isDisable" plain>提 交</el-button>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'
import VXEUtils from 'vxe-utils'
import VXETablePluginElement from 'vxe-table-plugin-element'
import 'vxe-table-plugin-element/dist/style.css'
import goodsSelect from '@/views/components/goodsPurchaseElSelect.vue'
import supplierSelect from '@/views/components/supplierElSelect.vue'
import {getWarehouse} from '@/api/basicInfo'
import { goodsUnitConversion, receiveCheckSubmit ,receiveSaveSubmit} from '@/api/inStorage'
import shipmentSelect from '@/views/components/shipmentSelect.vue'
import shipmentSelect3 from '@/views/components/shipmentSelect3.vue'
import warehouseSelect from '@/views/components/warehouseSelect.vue'

Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
VXETable.use(VXETablePluginElement)
export default {
  name: '新增收货单',
  components: {
    goodsSelect,
    shipmentSelect,
    supplierSelect,
    warehouseSelect,
    shipmentSelect3,
  },
  data() {
    return {
      allAlign:'center',
      warehouseData:[],
      units:[],
      isDisable:false,   //确定键显示按钮
      form: {
        shipmentCode: '',
        type:'0',
        warehouseCode:"",
        sourceCode:'',
        status:0,
        supplierCode:'',
        remarks: '', // 备注
        gmtPlanArrival: '',
        receiveItemList: []
      },
      loading: false,
      tableData: [
      ],
      rules: {
        shipmentCode: [
          { required: true, message: '请选择入驻商', trigger: 'change' }
        ],
        warehouseCode: [
          { required: true, message: '请选择仓库', trigger: 'change' }
        ],
        // supplierCode: [
        //   { required: true, message: '请选择供应商', trigger: 'change' }
        // ],
        sourceCode: [
          { max: 18, message: '来源单号不能超过18位', trigger: 'change'}
        ],
        remarks: [
          { max: 100, message: '备注不能超过100字符', trigger: 'change'}
        ],

      },
      validRules: {
        goodsName: [
          { required: true, message: '请选择商品' },
        ],
        goodsUnitName: [
          { required: true, message: '单位必须填写' },
        ],
        planQuantity: [
          { required: true, message: '数量必须填写' },
          { pattern: /^(?!0\d|[0.]+$)\d{1,20}(\.\d{1,6})?$/, message: '必须输入大于0且小数点不超过6位' },
          { max: 20, message: '数量不能超过20位'}
          // { pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d{0,6})$/, message: '数量必须大于0' }
        ],
      },
      listQuery: {
        page: 1,
        limit: 13,
        totalzong: 0
      },
    }
  },
  created() {
    // this.getWarehouse()
  },
  methods: {
    //选择供应商
    setsupplierCode(value){
      this.form.supplierCode = value.code;
      this.tableData = [];

    },
    // 选择入驻商
    setShipmentInfo(info) {
      this.form.shipmentCode = info.partyCode;
      this.form.shipmentName = info.userName;
      this.tableData = [];
      // this.$refs.warehouseSelect.init(this.form.shipmentCode)
    },
    // 选择仓库
    setWarehouseCode(value){
      this.form.warehouseCode = value;
      this.tableData = [];
      // this.$refs.shipmentSelect3.changeValue('')
      // this.form.shipmentCode = '';
      // this.form.shipmentName = '';
      // this.$refs.shipmentSelect3.setSelectValue(this.form.warehouseCode, this.form.shipmentCode);
    },

    //仓库查询
    getWarehouse(){
      getWarehouse().then(response => {
        this.warehouseData = response.data
      })
    },
    //计算基本单位
    nameChangeEvent (row) {
      const sd = row.goodsUnitConversionList.find(i => i.unitName == row.goodsUnitName)
      row.goodsUnit = sd.unitCode
      row.goodsUnitName = sd.unitName
      row.unitConvertQuantity = sd.quantity
      row.unit = '1' + row.goodsUnitName + '=' + row.unitConvertQuantity + row.basicUnitName
      row.basicQuantity = sd.quantity
    },
    //商品选择
    setGoodsCode(row){
      let obj = this.$refs.goodsSelect.obj
      row.goodsName = obj.name
      row.goodsCode = obj.code
      row.goodCode = obj.goodCode
      row.unitName = obj.unitName
      row.unitCode = obj.unitCode
      row.goodsBarCode = obj.barCode
      row.basicUnit = obj.unitCode
      row.basicUnitName = obj.basicUnitName
      row.spec = obj.spec
      row.expirationQuantity = obj.quality
      row.goodsUnitConversionList = obj.goodsUnitConversionList
      // 清空单位
      row.goodsUnit = ''
      row.goodsUnitName = ''
      if(row.goodsUnitConversionList.length === 1){
        row.goodsUnitName = row.goodsUnitConversionList[0].unitName
        this.nameChangeEvent (row)
      }
    },

    // 删除行
    removeRow(row){
      this.$refs.xTable.remove(row)
      // 刷新合计，避免因为删除操作而导致合计没法捕获数据变化
      this.$refs.xTable.updateFooter()
    },
    // 公共取消
    fatherItemCancel(modelFlag) {
      switch (modelFlag) {
        case 'add':
          this.modelAddFlag = false
          break
        case 'edit':
          this.modelEditFlag = false
          break
        default:
      }
    },
    // 新增
    insertEvent () {
      if (this.form.shipmentCode) {
        const xTable = this.$refs.xTable
        const newRow = {
        }
        xTable.insert().then(({ row }) => xTable.setActiveRow(row))

      } else {
        this.$message.error('入驻商不能为空')
      }

    },
    // 校验是否存在重复商品+单位的数据
    validDuplication(data){
      let validDuplicationMap = new Map();
      let key;
      let flag = true;
      data.forEach((e, index, list)=>{
        key = e.goodsCode + '-' + e.goodsUnit;
        if(validDuplicationMap.has(key)){
          this.$message.error(`商品“${e.goodsName}”存在相同单位的数据，不能保存`);
          flag = false;
          return false;
        }
        validDuplicationMap.set(key, key);
      })
      return flag;
    },
    // 提交数据 - 保存 or 提交
    async submitData(type) {
      const validateForm = await this.$refs['form'].validate()
      if (validateForm) {
        const vxeTableData = this.$refs.xTable.tableData
        if (!vxeTableData.length) {
          this.$message.error('请新增明细')
          return
        }
        this.form.receiveItemList = vxeTableData
        const errMap = await this.$refs.xTable.validate().catch(errMap => errMap)
        if (!errMap) {
          // 校验数据重复
          if(!this.validDuplication(this.form.receiveItemList)) {
            return ;
          }

          this.isDisable = true
          const requestOperation = [ receiveSaveSubmit,  receiveCheckSubmit ]
          requestOperation[type](this.form).then(res => {
            this.$message({ message: res.msg, type: 'success' })
            this.$emit('fatherAddMethod')
          }).then(() => {
            this.$eventBus.$emit('refreshList')
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({
              path: "/inbound/reciveList"
            });
          }).finally(() => this.isDisable = false)
        }
      }
    },
    // 计算总量
    handleSum(data){
      let count = 0
      data.forEach(row => {
        count += Number(isNaN(row.unitConvertQuantity * row.planQuantity)?0:row.unitConvertQuantity * row.planQuantity)
      })
      return parseFloat(count)
    },

    footerMethod ({ columns, data }) {
      return [
        columns.map((column, columnIndex) => {
          if (columnIndex === 1) {
            return '合计'
          }

          if (['sumBasicQuantity'].includes(column.property)) {
            return this.handleSum(data).toFixed(6)
          }
          if (['planQuantity', 'quantity'].includes(column.property)) {
              return parseFloat(XEUtils.sum(data, column.property)).toFixed(6)
          }
          return '-'
        })
      ]
    }
  }
}
</script>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 80px auto;
    width: 175px;
    // float: right;
  }
  </style>

<style>
.vxe-table .vxe-body--column:not(.col--ellipsis), .vxe-table .vxe-footer--column:not(.col--ellipsis), .vxe-table .vxe-header--column:not(.col--ellipsis) {
 padding: 6px 0;
}
.vxe-toolbar{padding:0 0 10px 0}
</style>
